
import os,sys,time
class parse_class:
    parse_dct={
                'css':{'start':'/* css */','end':'/* css */'},
                'head':{'start':'<!-- head -->','end':'<!-- head -->'},
                'body':{'start':'<!-- body -->','end':'<!-- body -->'},
                'var':{'start':'// var','end':'// var'},
                'data':{'start':'// data','end':'// data'},
                'methods':{'start':'// methods','end':'// methods'},
                'js2':{'start':'// javascript2','end':'// javascript2'}
            }
    parse_dct2={'template':{'start':'<!-- 使用template:','end':'-->'},}
    parse_script1={'start':'<script','end':'</script>'}
    parse_script2={'start':'src="','end':'/static_dir'}
    parse_css1={'start':'<link','end':'>'}
    parse_css2={'start':'href="','end':'/static_dir'}
    
    parse_dct3={'css':{'start':'/* css */','end':'/* css */'},
                'head':{'start':'<!-- head -->','end':'<!-- head -->'},
                'body':{'start':'<!-- body -->','end':'<!-- body -->'},
                'var':{'start':'// var','end':'// var'},
                'js':{'start':'// js','end':'// js'},}
    parse_dct4={
                'head':{'start':'<!-- head -->','end':'<!-- head -->'},
                'body':{'start':'<!-- body -->','end':'<!-- body -->'},
                'var':{'start':'// var','end':'// var'},
                'js':{'start':'// js','end':'// js'},
                'js2':{'start':'// javascript2','end':'// javascript2'},
            }
    def __init__(self,path,**kwargs):
        self.path=path
        
        self.static=kwargs.get('static','/static')
    
    #读取目标的起始和结束
    def get_infox(self,data,item=None,one=False,strip=False):
        """
        one:是否只根据条件只搜索一个
        data:<div><scc></scc></div> <div><scc></scc></div> <div><scc></scc></div>
        item:{'start':'<div>','end':'</div>'}
        res:[[0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>'], [0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>'], [0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>']]
        """
        res=[]
        while 1:
            try:
                idx1=data.find(item['start'])
                if idx1==-1:raise Exception('11111')
                idx2=idx1+len(item['start'])
                idx3=idx2+data[idx2:].find(item['end'])
                if idx3==-1:raise Exception('22222')
                idx4=idx3+len(item['end'])
                data1=data[idx1:idx4]
                data2=data[idx2:idx3]
                if strip is True:
                    data2=data2.strip()
                res.append([idx1,idx2,idx3,idx4,data1,data2])
                if one is True:break
                data=data[idx4:]
            except :break
        return res
    def get_infox2(self,data,parse_dct,strip=False):
        """
            根据parse_dct 合成
            strip:是否清除data2前后的空格
        """
        res={}
        for key in parse_dct:
            item=parse_dct[key]
            res_item=self.get_infox(data,item,strip=strip)
            res[key]=res_item
        return res
    
    
    #读取html文件内的内容
    def read_html(self,template_name='',file_pathx=None):
        file_path=self.path+os.sep+template_name+os.sep+'main.html'
        if file_pathx is not None:file_path=file_pathx
        #############替换 hntl内容 <使用template:
        with open(file_path, "r", encoding="utf-8")as f:
            data = f.read()
        return data
def test(main_html_path,web_template_path,**kwargs):
    p=parse_class(web_template_path,**kwargs)
    #首先获取main.html内容
    main_html=p.read_html(file_pathx=main_html_path)
    #然后解析出main.html使用多少模板
    use_template=p.get_infox2(main_html,parse_dct=p.parse_dct2,strip=True)
    #use_template:{'template': [[522, 538, 542, 545, '<!-- 使用template:侧边栏 -->', '侧边栏'], [76, 92, 97, 100, '<!-- 使用template:导航标签 -->', '导航标签'], [21, 37, 40, 43, '<!-- 使用template:用户 -->', '用户'], [76, 92, 96, 99, '<!-- 使用template:标签页 -->', '标签页'], [76, 92, 98, 101, '<!-- 使用template:底部状态栏 -->', '底部状态栏']]}
    #然后遍历use_template 读取模板数据
    template_info_dct={}#存放模板数据
    template_head=set()#存放模板head
    for item in use_template['template']:
        template_name=item[5]
        template_name2=item[4]
        #读取模板的html
        template_html=p.read_html(template_name=template_name)
        #解析模板的html
        template_info=p.get_infox2(template_html,parse_dct=p.parse_dct)
        #template_info:{'css': [], 'head': [[38, 51, 382, 395, '<!-- head -->\n<script type="text/javascript"  src="../static_dir/vue2.5.17.js"></script>\n<script type="text/javascript"  src="../static_dir/element_ui_2.0.3_index.js"></script>\n<link rel="stylesheet" href="../static_dir/csx.css">\n<link rel="stylesheet" href="../static_dir/iconfont.css">\n<link rel="stylesheet" href="../static_dir/el_vue.css">\n<!-- head -->', '\n<script type="text/javascript"  src="../static_dir/vue2.5.17.js"></script>\n<script type="text/javascript"  src="../static_dir/element_ui_2.0.3_index.js"></script>\n<link rel="stylesheet" href="../static_dir/csx.css">\n<link rel="stylesheet" href="../static_dir/iconfont.css">\n<link rel="stylesheet" href="../static_dir/el_vue.css">\n']], 'body': [[415, 428, 485, 498, '<!-- body -->\n    <el-footer>\n        2022-22-22\n    </el-footer>\n    <!-- body -->', '\n    <el-footer>\n        2022-22-22\n    </el-footer>\n    ']], 'v
        for key in template_info:
            #body直接更改
            if key=='body':
                temp_idx1,temp_idx2,_,_,_,_=p.get_infox(main_html,{'start':template_name2,'end':''})[0]
                main_html=main_html[:temp_idx1]+template_info[key][0][5]+main_html[temp_idx2:]
            #head 修改路径 并且 去重
            elif key=='head':
                # parse_script1={'start':'<script','end':'</script>'}
                # parse_script2={'start':'src="','end':'/static_dir'}
                # parse_css1={'start':'<link','end':'>'}
                # parse_css2={'start':'href="','end':'/static_dir'}
                for itteem in template_info['head']:
                    script_lst=p.get_infox(itteem[4],p.parse_script1)
                    for iiitem in script_lst:
                        html_val=iiitem[4]
                        idx1,idx2,idx3,idx4,data1,data2=p.get_infox(html_val,p.parse_script2)[0]
                        html_val=html_val[:idx2]+p.static+html_val[idx4:]
                        html_val=html_val.strip()
                        if html_val not in template_head:template_head.add(html_val)
                    css_lst=p.get_infox(itteem[4],p.parse_css1)
                    for iiitem in css_lst:
                        html_val=iiitem[4]
                        idx1,idx2,idx3,idx4,data1,data2=p.get_infox(html_val,p.parse_css2)[0]
                        html_val=html_val[:idx2]+p.static+html_val[idx4:]
                        html_val=html_val.strip()
                        if html_val not in template_head:template_head.add(html_val)
            else:
                #其他的 堆一块 如css  js
                if template_info_dct.get(key)is None:template_info_dct[key]=''
                if template_info[key]!=[]:
                    template_info_dct[key]='\n'+template_info[key][0][5]+template_info_dct[key]
                
    #head 包装好
    template_head=list(template_head)
    template_head.sort(key=lambda tt:'vue'not in tt)
    template_info_dct['head']='\n'.join(list(template_head))
    #将head css js更改到main_html上
    for key in template_info_dct:
        
        zz=p.get_infox(main_html,p.parse_dct[key])
        _,idx2,_,_,_,_=zz[0]
        main_html=main_html[:idx2]+template_info_dct[key]+main_html[idx2:]
    
    return main_html

#解析需要动态加载的组件  将组件中的css js head保存到静态文件夹下 方便客户端调用
#如标签页-工艺设定-查看工艺 
#检索到该文件夹下的init文件后 会解析main.html文件 然后将
#  独立的css封装到/static/如标签页-工艺设定-查看工艺/main.css
#  独立的js封装到/static/如标签页-工艺设定-查看工艺/main.js
#在客户端加载组件的时候 会收到 css和js的静态路由以及body内的html代码 ，客户端会优先加载css和html 最后再加载js
def parse_init(abs_web_template_path,web_template_path,**kwargs):
    """
    web_template_dir_path
    """
    static_path=kwargs.get('static')
    p=parse_class(abs_web_template_path,**kwargs)
    #读取模板文件夹下面的文件夹
    for item in os.listdir(abs_web_template_path):
        #判断init是否存在
        if os.path.exists(abs_web_template_path+os.sep+item+os.sep+'init') is True:
            #既然存在  就表示这是一个需要动态加载的组件 接下来就开始文件解析
            #获取html文件路径
            html_path=abs_web_template_path+os.sep+item+os.sep+'main.html'
            #获取html内容
            try:
                template_html=p.read_html(file_pathx=html_path)
            except:
                template_html=''
                continue
            #准备解析文件的 head css var js body的内容
            template_info=p.get_infox2(template_html,parse_dct=p.parse_dct3)
            # head 暂时先不处理 懒 暂时用不着
            # css 
            try:
                css_str=template_info['css'][0][5]
            except:
                css_str=''
            new_static_path=static_path+os.sep+item
            try:os.makedirs(new_static_path)
            except:pass
            css_static_path=new_static_path+os.sep+'main.css'
            with open(css_static_path,'w',encoding='utf-8')as f:
                print('设置静态文件css_static_path',css_static_path)
                f.write(css_str)
            # body 
            body_str=template_info['body'][0][5]
            # var  js 
            try:
                var_str=template_info['var'][0][5]
            except:
                var_str=''
            try:
                js_str=template_info['js'][0][5]
            except:
                js_str=''
            css_static_path=new_static_path+os.sep+'main.js'
            with open(css_static_path,'w',encoding='utf-8')as f:
                f.write(var_str+'\n'+js_str)

def my_vue_js(dir_path,static_path):
    str_js=''
    str_css=''
    #读取模板文件夹下面的文件夹
    lstdir=sorted([dir_path+os.sep+item for item in os.listdir(dir_path) if os.path.isdir(dir_path+os.sep+item)],key=lambda item:int(os.path.basename(item).split('_')[0]))
    for new_dir_path in lstdir:
        try:
            with open(new_dir_path+os.sep+'main.js','r',encoding='utf-8')as f:
                str_js+=f.read()
        except Exception as e:print(e)
        try:
            with open(new_dir_path+os.sep+'main.css','r',encoding='utf-8')as f:
                str_css+=f.read()
        except Exception as e:print(e)
    # print('vue_js load',dir_path)
    # print('vue_js save',js_path)
    with open(static_path+os.sep+'base_vue_template.js','w',encoding='utf-8')as f:
        f.write(str_js)
    with open(static_path+os.sep+'base_vue_template.css','w',encoding='utf-8')as f:
        f.write(str_css)
def load_dongtai_js(js_lst,abs_web_template_path):
    js_str=''
    for template_name in js_lst:
        js_path=abs_web_template_path+os.sep+template_name+os.sep+'main.js'
        
        try:
            
            print(r'111%%%%%%%%%%%%%%%%%%%%%%%',js_path)
            with open(js_path,'r',encoding='utf-8',) as f:
                template_js=f.read()
        except Exception as e:
            print(r'222%%%%%%%%%%%%%%%%%%%%%%%',e)
            template_js=''
        js_str=js_str+'\n'+template_js
    return js_str
#动态组件解析 返回body内容 以及 css_path 和js_path
#{'css':True,'css_path':xxxxx,'js':True,'js_path':xxxxx,'body':True,'body_html':'xxxxx'}
def parse_dongtai(template_name,abs_web_template_path,web_template_path,**kwargs):
    """
    web_template_dir_path
    """
    static_dir=kwargs.get('static')
    # res={'css':True,'css_path':'','js':True,'js_val':'','body':True,'body_val':''}
    res={'js_val1':'','js_val2':'','head':[],'body_val':''}
    p=parse_class(abs_web_template_path,**kwargs)
    #读取模板html
    html_path=abs_web_template_path+os.sep+template_name+os.sep+'main.html'
    #获取html内容
    try:
        template_html=p.read_html(file_pathx=html_path)
    except:
        template_html=''
    #准备解析文件的 body的内容
    # parse_dct4={
                # 'head':{'start':'<!-- head -->','end':'<!-- head -->'},
    #             'body':{'start':'<!-- body -->','end':'<!-- body -->'},
    #             'var':{'start':'// var','end':'// var'},
    #             'js':{'start':'// js','end':'// js'},
    #             'js2':{'start':'// javascript2','end':'// javascript2'},
    #         }
    template_info=p.get_infox2(template_html,parse_dct=p.parse_dct4)
    #获取css和js路径
    new_static_dir=static_dir+os.sep+template_name
    #css
    css_static_path=new_static_dir+os.sep+'main.css'
    #js
    js_static_path=new_static_dir+os.sep+'main.js'
    print('css_static_path',css_static_path,os.path.exists(css_static_path))
    if  os.path.exists(css_static_path) is True:
        res['head'].append(web_template_path+os.sep+template_name+os.sep+'main.css')
    #head
    # print('ttttestt',res['head'])
    # print('testwe',template_info['head'])
    for itteem in template_info['head']:
        script_lst=p.get_infox(itteem[4],p.parse_script1)
        for iiitem in script_lst:
            html_val=iiitem[4]
            """
        one:是否只根据条件只搜索一个
        data:<div><scc></scc></div> <div><scc></scc></div> <div><scc></scc></div>
        item:{'start':'<div>','end':'</div>'}
        res:[[0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>'], [0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>'], [0, 5, 16, 22, '<div><scc></scc></div>', '<scc></scc>']]
        """
            
            # parse_script1={'start':'<script','end':'</script>'}
            # parse_script2={'start':'src="','end':'/static_dir'}
            idx1,idx2,idx3,idx4,data1,data2=p.get_infox(html_val,p.parse_script2)[0]
            html_val=web_template_path+html_val[idx4:iiitem[2]-iiitem[3]]
            html_val=html_val.strip()
            html_val=html_val.rstrip(">")
            html_val=html_val.rstrip('"')
            html_val=html_val.rstrip("'")
            print(html_val)
            if html_val not in res['head']:res['head'].append(html_val)
        css_lst=p.get_infox(itteem[4],p.parse_css1)
        for iiitem in css_lst:
            html_val=iiitem[4]
            idx1,idx2,idx3,idx4,data1,data2=p.get_infox(html_val,p.parse_css2)[0]
            html_val=web_template_path+html_val[idx4:iiitem[2]-iiitem[3]]
            html_val=html_val.strip()
            html_val=html_val.strip(">")
            html_val=html_val.strip('"')
            html_val=html_val.strip("'")
            if html_val not in res['head']:res['head'].append(html_val)
    # print('ttttestt',res['head'])
    # body 
    try:
        body_str=template_info['body'][0][5]
        res['body_val']=body_str
    except:
        res['body_val']='parse.py error 1 错误'
    try:
        temp=template_info['var'][0][5]
        res['js_val1']=temp
    except:
        res['js_val1']='parse.py error 2 错误'
    try:
        temp=template_info['js'][0][5]
        res['js_val1']=res['js_val1']+'\n'+temp
    except:
        res['js_val1']='parse.py error 3 错误'
    try:
        temp=template_info['js2'][0][5]
        res['js_val2']=temp
    except:
        # print('javascript2',template_info.get('javascript2'))
        # input('...')
        res['js_val2']='parse.py error 4 错误'
    # print(res)
    # res={'head':[],
    #         'js_val1':'''
    #         window.ttttttttteeeessssttdata=[
    #             {'content':'控制中心'},
    #             {'content':'查看设备'}
    #         ]
    #         new Vue({
    #             el:'#ttttttttteeeesssstt',
    #              data: {// data
    #                 ttttttttteeeessssttdata: window.ttttttttteeeessssttdata,
    #                 // data
    #              },
    #            })''', # 加载body_val时才加载的
    #         'js_val2':"""console.log(window.ttttttttteeeessssttdata);window.ttttttttteeeessssttdata[0].content='rrr'""",    # 无论如何都要加载的
    #         'body_val':"""<el-breadcrumb id='ttttttttteeeesssstt' separator="/" style="width: 80%;float:left;margin: 25px;">
    #         <el-breadcrumb-item  v-for="item in ttttttttteeeessssttdata">{{item.content}}</el-breadcrumb-item>
    #     </el-breadcrumb>""",
    #         }
    return res
if __name__=='__main__':
    path1=r'F:\昆明兑悦科技有限公司\永生花加工软件\web\main.html'
    path2='F:\昆明兑悦科技有限公司\永生花加工软件\web\web_template'
    test_static=r'F:\昆明兑悦科技有限公司\永生花加工软件\web\web_template\static_dir'
    res=parse_dongtai(template_name='标签页-工艺设定-查看工艺',abs_web_template_path=path2,web_template_path='/static',static=test_static)
    
    # res=test(path1,path2,static=test_static)
    with open(r'C:\Users\Admin\Desktop\ttttttttest.html','w',encoding='utf-8')as f:
        f.write(str(res))
    res=parse_init(abs_web_template_path=path2,web_template_path='/static',static=test_static)